<?php
/**
 * Created by JetBrains PhpStorm.
 * User: AndreyG
 * Date: 26.01.12
 * Time: 13:06
 * To change this template use File | Settings | File Templates.
 */
class Company_Model extends My_Model
{

    protected function _init()
    {
        $this->_table = 'company';
    }

    public function getCollection(array $where = null, array $order = null)
    {
        if(is_array($where) && count($where) > 0) {
            $whereTerm = implode(' AND ', $where);
        } else {
            $whereTerm = 1;
        }

        if(!is_array($order)) {
            $order['field'] = 'company.name';
            $order['dir'] = 'DESC';
        }

        $this->db->query(
            "SELECT company.*, location.title AS location, company_rating.rating AS rating, GROUP_CONCAT(' ',category.title) AS category
            FROM company
            LEFT JOIN location ON company.location_id = location.id
            LEFT JOIN company_has_category ON company.id = company_has_category.company_id
            LEFT JOIN category ON category.id = company_has_category.category_id
            LEFT JOIN company_rating ON company.id = company_rating.company_id
            WHERE {$whereTerm}
            GROUP BY company.id
            ORDER BY {$order['field']} {$order['dir']};"
        );

        $results = array();

        while($row = $this->db->next()) {
            $_model = new Company_Model();
            $_model->setData($row);
            $results[] = $_model;
        }

        reset($results);
        return $results;

    }

    public function save()
    {
        parent::save();

        if(array_key_exists('rating', $this->_data)) {
            $this->db->pdo->query(
                "INSERT INTO company_rating (company_id, rating)
                VALUES({$this->getId()}, ".(int)$this->getRating().");"
            );
        }

        if(array_key_exists('category', $this->_data)) {
            foreach($this->getCategory() as $key => $value) {
                $this->db->pdo->query(
                    "INSERT INTO company_has_category (company_id, category_id)
                VALUES({$this->getId()}, ". (int)$value .");"
                );
            }
        }

    }
}
